package com.huicoo.forestmanager.ui.patrol.forestCampTask;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.VideoView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.huicoo.forestmanager.CustomUtils;
import com.huicoo.forestmanager.R;
import com.huicoo.forestmanager.adapter.PatrolNeedVerifyProblemAdapter;
import com.huicoo.forestmanager.base.BaseFragment;
import com.huicoo.forestmanager.base.BaseRecyclerItemDecoration;
import com.huicoo.forestmanager.network.bean.patrol.PatrolEventEntity;
import com.huicoo.forestmanager.network.bean.patrol.UploadFileBean;
import com.huicoo.forestmanager.network.bean.patrol.VerifyEventCommentBean;
import com.huicoo.forestmanager.others.Constants;
import com.huicoo.forestmanager.others.EventReplyEvent;
import com.huicoo.forestmanager.others.GetCommentEvent;
import com.huicoo.forestmanager.ui.media.BrowseImageActivity;
import com.huicoo.forestmanager.ui.patrol.forestCampTask.contract.ForestCampTaskVerifyEventContract;
import com.huicoo.forestmanager.ui.patrol.forestCampTask.presenter.ForestCampTaskVerifyEventPresenter;
import com.huicoo.forestmanager.ui.web.CustomWebActivity;
import com.huicoo.forestmanager.util.AttachmentHelper;
import com.huicoo.forestmanager.util.DisplayUtil;
import com.huicoo.forestmanager.util.LogUtils;
import com.huicoo.forestmanager.util.SharedPreferenceUtil;
import com.huicoo.forestmanager.util.WeakHandler;
import com.huicoo.forestmanager.util.audio.PlayAudioRecordDialog;
import com.huicoo.forestmanager.util.toast.ToastUtils;
import com.huicoo.forestmanager.widget.LoadingDialog;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

/**
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2019/4/7		    Administrator
 * 进行巡查任务--需进一步核实的问题的片断
 */
public class NeedVerifyProblemContainerFragment extends BaseFragment implements ForestCampTaskVerifyEventContract.View, PatrolNeedVerifyProblemAdapter.OnAttachmentListener {
    @BindView(R.id.rv_problem)
    RecyclerView rv_problem;

    private PatrolNeedVerifyProblemAdapter adapter;

    private LoadingDialog loadingDialog;

    private WeakHandler handler;

    public static NeedVerifyProblemContainerFragment getInstance() {
        return new NeedVerifyProblemContainerFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_need_verify_problem_container;
    }

    @Override
    protected void initView() {
        initRecyclerView();

        loadingDialog = new LoadingDialog(getActivity());

        presenter = new ForestCampTaskVerifyEventPresenter(this);
        handler = new WeakHandler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == 333) {
                    LogUtils.v("gogogo handler message = " + (String) (msg.obj));
                    playVideo((String) msg.obj);
                }
                return false;
            }
        });
    }

    private void initRecyclerView() {
        //设置布局管理器
        rv_problem.setLayoutManager(new LinearLayoutManager(getContext()));
        //创建适配器
        adapter = new PatrolNeedVerifyProblemAdapter(null);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                try {
                    PatrolEventEntity entity = (PatrolEventEntity) adapter.getData().get(position);
                    String baseUrl = SharedPreferenceUtil.LoadStringData(Constants.PROJECT_NAME, Constants.BASE_URL);
                    String url = CustomUtils.urlAddParams(getContext(), baseUrl + "h5/eventHandleDetail.html") + "&id=" + entity.getID();
                    LogUtils.v("gogogo event detail url = " + url);
                    Intent intent = new Intent(getContext(), CustomWebActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("url", url);
                    intent.putExtras(bundle);
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        adapter.setOnAttachmentListener(this);
        //设置适配器
        rv_problem.setAdapter(adapter);
        rv_problem.addItemDecoration(new BaseRecyclerItemDecoration(0, 0, 0, 2));
    }


    public void setData(List<PatrolEventEntity> rows) {
        if (adapter != null) {
            adapter.setNewData(rows);
        }
    }

    public void initSetData(List<PatrolEventEntity> rows) {
        if (adapter != null && adapter.getData().isEmpty()) {
            adapter.setNewData(rows);
        }
    }

    // 播放录音
    private void playVoice(String path) {
        if (TextUtils.isEmpty(path)) {
            return;
        }
        Activity activity = getActivity();
        if (activity == null) {
            return;
        }
        PlayAudioRecordDialog dialog = new PlayAudioRecordDialog(activity);
        dialog.showDialog(path, new PlayAudioRecordDialog.OnPlayVoiceErrorListener() {
            @Override
            public void onError() {
                ToastUtils.show("录音播放异常，请重试");
            }
        });
    }

    // 播放视频
    private void playVideo(String path) {
        LogUtils.v("gogogo play path = " + path);
        if (TextUtils.isEmpty(path)) {
            return;
        }
        Activity activity = getActivity();
        if (activity == null) {
            return;
        }
        Dialog dialog = new Dialog(activity, R.style.PlayVideoDialog);
        dialog.setCanceledOnTouchOutside(false);
        //创建video view
        RelativeLayout relativeLayout = new RelativeLayout(activity);
        VideoView mVideoView = new VideoView(activity);
        mVideoView.setVideoPath(path);
        mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                LogUtils.v("gogogo play video complete");
                dialog.dismiss();
            }
        });
        mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                LogUtils.v("gogogo play video fail");
                dialog.dismiss();
                boolean isDelete = AttachmentHelper.deleteFile(path);
                LogUtils.v("gogogo delete file = " + isDelete);
                ToastUtils.show("视频播放异常，请重试");
                return false;
            }
        });
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        relativeLayout.addView(mVideoView, layoutParams);
        //dialog添加view
        ViewGroup.LayoutParams rootLayoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        dialog.setContentView(relativeLayout, rootLayoutParams);
        Window mWindow = dialog.getWindow();
        if (mWindow != null) {
            WindowManager.LayoutParams lp = mWindow.getAttributes();
            int mScreenWidth = DisplayUtil.getScreenWidth(activity);
            int mScreenHeight = DisplayUtil.getScreenHeight(activity);
            lp.width = mScreenWidth; // 宽度
            lp.height = (int) (mScreenHeight * 0.6); // 高度
            mWindow.setAttributes(lp);
        }
        dialog.show();
        mVideoView.start();
    }

    @Override
    public void downloadSuccess(int type, String filePath) {
        LogUtils.v("gogogo download success = " + type + " -- " + filePath);
        ToastUtils.show("下载完成");
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        Message msg = new Message();
        msg.what = 333;
        msg.obj = filePath;
        handler.sendMessageDelayed(msg, 300);
    }

    @Override
    public void uploadFileSuccess(UploadFileBean.UploadFileData Data, int attachmentType, int during) {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

    @Override
    public void replyEventSuccess() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        EventBus.getDefault().post(new EventReplyEvent());
    }

    @Override
    public void verifyEventSuccess() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        ToastUtils.show("核实事件成功");
    }

    @Override
    public void getCommentSuccess(List<VerifyEventCommentBean.EventCommentEntity> commentList, int totalNum) {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        EventBus.getDefault().post(new GetCommentEvent(totalNum, commentList));
    }

    @Override
    public void fail(String msg) {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        ToastUtils.show(msg);
    }

    @Override
    public void clickMediaAttachment(int type, String path, String filename) {
        //点击查看多媒体附件
        LogUtils.v("gogogo 点击多媒体附件 = " + path + "  --  " + filename);
        if (type == 1) {
            playVoice(path);
        } else {
            tryToPlayVideo(type, path, filename);
        }
    }

    private void tryToPlayVideo(int type, String path, String filename) {
        File file = new File(AttachmentHelper.getFilePath(filename));
        if (file.exists()) {
            playVideo(file.getAbsolutePath());
        } else {
            if (loadingDialog != null) {
                loadingDialog.show();
            }
            ((ForestCampTaskVerifyEventPresenter) presenter).download(type, path, filename);
        }
    }

    @Override
    public void clickPicAttachment(String path) {
        //点击查看图片附件
        LogUtils.v("gogogo 点击图片附件 = " + path);
        Bundle bundle = new Bundle();
        bundle.putString("imgUrl", path);
        Intent intent = new Intent(getActivity(), BrowseImageActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);
    }
}
